<!-- 这里是Homne下的用户管理 -> 用户列表界面 -->
<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图展示区 -->
    <el-card class="box-card">
        <div  class="text item">
            <!-- 使用栅格式布局 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <!-- 搜索区域 -->
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>

            <!-- 显示用户列表区 -->
            <el-table :data="userlist" border stripe>
                <el-table-column label="#" type="index"></el-table-column>
                <el-table-column label="姓名" prop="username"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="电话" prop="mobile"></el-table-column>
                <el-table-column label="角色" prop="role_name"></el-table-column>
                <el-table-column label="状态" prop="mg_state">
                    <template slot-scope="scope">
                        <!-- 渲染开关组件 -->
                        <el-switch v-model="scope.row.mg_state" @change="handleSwitchChanged(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" >
                    <template slot-scope="scope">
                        <!-- 渲染操作栏 -->
                        <!-- 修改按钮 -->
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
                        <!-- 删除按钮 -->
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUsers(scope.row.id)"></el-button>
                        <!-- 鼠标放上去在上面增加提示文字信息 -->
                        <!-- 分配角色按钮 -->
                        <el-tooltip content="分配角色" placement="top">
                            <el-button type="success" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed"
        >
        <!-- 内容主题区 -->
        <!-- 添加表单验证 -->
            <el-form label-width="70px" class="login_form" :model="addForm" :rules="addFormRules" ref="addFormRuleForm"> 
                <!-- 用户名 -->
                <el-form-item  label="用户名" prop="username" >
                    <el-input prefix-icon="iconfont icon-yonghuming" v-model="addForm.username" ></el-input>
                </el-form-item>
                 <!-- 密码 -->
                <el-form-item  label="密码" prop="password" >
                    <el-input prefix-icon="iconfont icon-yonghuming" v-model="addForm.password" ></el-input>
                </el-form-item>
                <!-- 邮箱 -->
                <el-form-item  label="邮箱" prop="email" >
                    <el-input prefix-icon="iconfont icon-yonghuming" v-model="addForm.email" ></el-input>
                </el-form-item>
                <!-- 手机 -->
                <el-form-item  label="手机号" prop="mobile" >
                    <el-input prefix-icon="iconfont icon-yonghuming" v-model="addForm.mobile" ></el-input>
                </el-form-item>
            </el-form>
        <!-- 底部区 -->
        <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog
    title="修改用户"
    :visible.sync="editDialogVisible"
    width="50%"
    @close="editDialogClosed"
    >
    <!-- 内容主题区 -->
        <!-- 添加表单验证 -->
            <el-form label-width="70px" class="login_form" :model="editForm" :rules="editFormRules" ref="editFormRuleForm"> 
                <!-- 用户名 -->
                <el-form-item  label="用户名" prop="username">
                    <el-input prefix-icon="iconfont icon-yonghuming" v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <!-- 邮箱 -->
                <el-form-item  label="邮箱" prop="email" >
                    <el-input prefix-icon="iconfont icon-yonghuming" v-model="editForm.email" ></el-input>
                </el-form-item>
                <!-- 手机 -->
                <el-form-item  label="手机号" prop="mobile" >
                    <el-input prefix-icon="iconfont icon-yonghuming" v-model="editForm.mobile" ></el-input>
                </el-form-item>
            </el-form>
        <!-- 底部区 -->
    <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
    </span>
    </el-dialog> 

     <!-- 分配角色对话框 -->
    <el-dialog
        title="添加用户"
        :visible.sync="setRoleDialogVisible"
        width="50%"
        @close="setRoleDialogClose"
        >
        <!-- 内容主题区 -->
        <div>
            <p>当前的用户：{{userInfo.username}}</p>
            <p>当前的角色：{{userInfo.role_name}}</p>
            <p>分配新角色：
                  <el-select v-model="selectedRoleId" placeholder="请选择">
                    <el-option
                    v-for="item in rolesList"
                    :key="item.id"
                    :label="item.roleName"
                    :value="item.id"
                    >
                    </el-option>
                </el-select>
            </p>
        </div>
        <!-- 底部区 -->
        <span slot="footer" class="dialog-footer">
            <el-button @click="setRoleDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
        </span>
    </el-dialog>



    <!-- 底部分页器 -->
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1,2,5,10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        >
        </el-pagination>
  </div>
</template>

<script>
export default {
  data () {
      //验证邮箱的规则
      var checkEmail = (rule, value, callback) => {
          //验证邮箱的正则表达式
          const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])/
          if(regEmail.test(value)) {
              //验证通过
              return callback()
          }else{
              callback(new Error('请输入合法的邮箱!'))
          }
      }
      //验证手机号的规则
      var checkMobile = (rule, value, callback) => {
          //验证手机号的正则表达式
          const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
          if(regMobile.test(value)) {
              //验证通过
              return callback()
          }else{
              callback(new Error('请输入合法的手机号!'))
          }
      }
    return {
        //用户列表的请求参数
        queryInfo:{
            query: '',
            pagenum: 1,
            pagesize: 2
        },
        //获取到的用户列表
        userlist: [],
        //获取到的用户列表总数
        total: 0,
        //控制添加用户对话框的显示与隐藏
        addDialogVisible: false,
        //添加用户的表单数据
        addForm: {
            username:' ',
            password:'',
            email:'',
            mobile:''
        },
        //添加表单的验证规则对象
        addFormRules:{
            username: [
                {required: true, message:'请输入用户名', trigger:'blur'},
                { min: 3, max: 10, message:'用户名的长度在 3 - 10 个字符之间'}
            ],
             password: [
                {required: true, message:'请输入密码', trigger:'blur'},
                { min: 6, max: 15, message:'密码的长度在 6 - 15 个字符之间'}
            ],
            email: [
                {required: true, message:'请输入邮箱', trigger:'blur'},
                {
                    validator: checkEmail, trigger:'blur'
                }
            ],
            mobile: [
                 {required: true, message:'请输入手机号', trigger:'blur'},
                { min: 6, max: 15, message:'手机号的的长度在 6 - 15 个字符之间'},
                {
                    validator: checkMobile, trigger:'blur'
                }
            ]
        },
        //控制修改用户对话框的显示与隐藏
        editDialogVisible: false,
        //查询到的用户信息对象
        editForm: {},
        //修改表单的验证规则对象
        editFormRules:{
            email: [
                {required: true, message:'请输入邮箱', trigger:'blur'},
                {
                    validator: checkEmail, trigger:'blur'
                }
            ],
            mobile: [
                 {required: true, message:'请输入手机号', trigger:'blur'},
                { min: 6, max: 15, message:'手机号的的长度在 6 - 15 个字符之间'},
                {
                    validator: checkMobile, trigger:'blur'
                }
            ]
        },
        //控制分配角色Dialog的显隐
        setRoleDialogVisible: false,
        //需要被分配角色的用户信息
        userInfo: {},
        //所有角色的数据列表
        rolesList: [],
        //保存选中后select的项
        selectedRoleId:''
    };
  },
  created() {
      //获取用户信息
      this.getUserList()
  },
  methods: {
      //发起获取用户信息请求
      async getUserList() {
         const { data:res } = await this.$http.get('users',{
              params: this.queryInfo
          })
          //判断请求是否获取成功
          if(res.meta.status !== 200) return this.$message.error("获取用户列表失败！")
          this.userlist = res.data.users
          this.total = res.data.total
      },
      //pageSize改变函数
      handleSizeChange(newSize) {
          //根据获取到的数据重新发起网络请求拿到数据
          this.queryInfo.pagesize = newSize
          this.getUserList()
      },
      //页码值改变函数
      handleCurrentChange(newPage) {
        this.queryInfo.pagenum = newPage
        this.getUserList()
      },
      //监听switch开关的改变
      async handleSwitchChanged(userState) {
          //修改用户请求
          const { data:res } = await this.$http.put(`users/${userState.id}/state/${userState.mg_state}`)
          //修改失败应该还原原来的值
          if(res.meta.status !== 200) {
          //修改失败还原原来的值
            userState.mg_state = !userState.mg_state
            return this.$message.error("更新用户状态状态失败！")
          }
          this.$message.success('更新用户状态成功！')
      },
      //Dialog表单关闭触发事件
      addDialogClosed() {
          //对话框关闭后重置表单数据
          this.$refs.addFormRuleForm.resetFields()
      },
      //点击添加用户
      addUser() {
          //表单预校验
          this.$refs.addFormRuleForm.validate(async valid => {
              if(!valid) return 
              //发起添加用户的网络请求
              const { data:res } = await this.$http.post('users', this.addForm)
              //判断请求是否成功
              if(res.meta.status !== 201) {
                  this.$message.error('添加用户失败')
              }else{
                  this.$message.success('添加用户成功')
                  //隐藏添加用户的对话框
                  this.addDialogVisible = false
                  //重新获取用户列表的数据
                  this.getUserList()
              }
          })
      },
      //展示编辑用户的对话框
      async showEditDialog(id) {
          //根据id获取用户信息请求
          const{ data:res} = await this.$http.get('users/' + id)
          if(res.meta.status !== 200) return this.$message.error("查询用户信息失败")
          this.editForm = res.data
          //展示对话框
          this.editDialogVisible = true
      },
      //Dialog表单关闭触发事件
      editDialogClosed() {
          this.$refs.editFormRuleForm.resetFields()
      },
      //修改用户信息并提交
      editUserInfo() {
          this.$refs.editFormRuleForm.validate(async valid => {
              if(!valid) return
              //发起修改用户数据请求
              const { data:res } = await this.$http.put('users/' + this.editForm.id, {
                  email: this.editForm.email,
                  mobile: this.editForm.mobile
              })
              //判断请求是否成功
              if(res.meta.status !== 200) this.$message.error("修改用户信息失败!")
              //关闭对话框
              this.editDialogVisible = false
              //刷新数据列表
              this.getUserList()
              //提示用户修改成功
              this.$message.success("修改用户信息成功!")
          })
      },
      //删除用户功能
      deleteUsers(id){
        //删除之前进行验证,防止用户误操作
        this.$confirm('您确定要永久删除该用户?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          //确定删除回调
          //发起请求
          const { data:res } = await this.$http.delete('users/' + id)
          if(res.meta.status !== 200){
              this.$message({
              type:'error',
              message: '删除失败!'
          })
          }else{
            this.$message({
                type: 'success',
                message: '删除成功!'
            });
            //更新数据
            this.getUserList()
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除!'
          });          
        });
      },
      //展示分配角色Dialog
      async setRole(userInfo) {
          //保存用户信息到data中
          this.userInfo = userInfo
          this.setRoleDialogVisible = true
          //在展示对话框之前获取所有角色列表
          const { data:res } = await this.$http.get('roles')
          if(res.meta.status !== 200) return this.$message.error('获取角色信息失败！')
          this.rolesList = res.data
      },
      //分配角色确定按钮
      async saveRoleInfo() {
        //如果用户没有选中任何信息
        if(!this.selectedRoleId)  return this.$message.error("请选择要分配的角色！")
        const { data:res } = await this.$http.put(`users/${this.userInfo.id}/role`,{
            rid: this.selectedRoleId
        })
        if(res.meta.status == 404){
            this.$message.error("分配角色失败！")
        }else if(res.meta.status == 400){
            this.$message.error("不允许修改管理员的信息！")
        }else{
            this.$message.success("分配角色成功！")
        }
        //同步更新数据并关闭对话框
        this.getUserList()
        this.setRoleDialogVisible = false
      },
      //关闭按钮
      setRoleDialogClose() {
          this.selectedRoleId = '',
          this.userInfo = ''
      }
  },
}

</script>
<style lang="less" scoped>
    
      
</style>